#include "Triangle.h"
#include <d3dx9.h>

static const int TRI_VERTEX_COUNT = 3;
static const int TRI_INDEX_COUNT = 3;

Triangle::~Triangle()
{
}

bool Triangle::CreateObject(IDirect3DDevice9* a_pDevice, char* a_pTexFileName)
{
	if(!a_pDevice)
	{
		return false;
	}

	//Create vertex buffer
	HRESULT result  = a_pDevice->CreateVertexBuffer(sizeof(VertexData) * TRI_VERTEX_COUNT, 0, VERTEX_FORMAT_FVF, D3DPOOL_DEFAULT, &m_pVertexBuffer, NULL);
	if(result != D3D_OK)
	{
		return false;
	}

	//Create index buffer
	result = a_pDevice->CreateIndexBuffer(sizeof(short) * TRI_INDEX_COUNT, 0, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_pIndexBuffer, NULL);
	if(result != D3D_OK)
	{
		m_pVertexBuffer->Release();
		m_pVertexBuffer = NULL;
		return false;
	}

	VertexData verts[TRI_VERTEX_COUNT];
	verts[0].pos = D3DXVECTOR3(-1, 1, 0);
	verts[0].col = D3DCOLOR_XRGB(0, 0, 255);

	verts[1].pos = D3DXVECTOR3(1, 0, 0);
	verts[1].col = D3DCOLOR_XRGB(0, 255, 0);

	verts[2].pos = D3DXVECTOR3(-1, -1, 0);
	verts[2].col = D3DCOLOR_XRGB(255, 0, 0);

	short indices[TRI_INDEX_COUNT];
	indices[0] = 0;
	indices[1] = 1;
	indices[2] = 2;

	void* pLockedData = NULL;
	m_pVertexBuffer->Lock(0, sizeof(VertexData) * TRI_VERTEX_COUNT, &pLockedData, 0);
	memcpy(pLockedData, verts, sizeof(VertexData) * TRI_VERTEX_COUNT);
	m_pVertexBuffer->Unlock();
	pLockedData = NULL;

	m_pIndexBuffer->Lock(0, sizeof(short) * TRI_INDEX_COUNT, &pLockedData, 0);
	memcpy(pLockedData, indices, sizeof(short) * TRI_INDEX_COUNT);
	m_pIndexBuffer->Unlock();
	pLockedData = NULL;

	return true;
}

void Triangle::Render(float a_dt, IDirect3DDevice9 *a_pDevice, const RenderParams& a_renderParams)
{
	if(a_pDevice && m_pVertexBuffer && m_pIndexBuffer)
	{
		D3DXMATRIX translationMat;
		D3DXMatrixTranslation(&translationMat, 2, 0, 0);

		D3DXMATRIX rotationMat;
		D3DXMatrixRotationY(&rotationMat, 1.0f);

		D3DXMATRIX modelToWorld;
		D3DXMatrixMultiply(&modelToWorld, &rotationMat, &translationMat);

		a_pDevice->SetTransform(D3DTS_WORLD, &modelToWorld);

		a_pDevice->SetStreamSource(0, m_pVertexBuffer, 0, sizeof(VertexData));
		a_pDevice->SetFVF(VERTEX_FORMAT_FVF);

		a_pDevice->SetIndices(m_pIndexBuffer);
		a_pDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, TRI_VERTEX_COUNT, 0, 1);
	}
}